import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import { Injectable } from '@angular/core';
import { DFConfigApi } from '../../app.config';
import { LocalStorage } from '../../app.localStorage';

@Injectable()
export class DFHttp{
    constructor(private http:Http,private storage:LocalStorage){
    }

    /**
     * get 请求
     * 
     * @param {any} url 
     * @param {any} [params] 
     * @returns {Observable<any>} 
     * @memberof DFHttp
     */
    get(url,params?):Observable<any>{
        url +='?';
        for(let key in params){
            url+= `${key}=${params[key]}`+'&&';   
        }
        return this.http.get(url).catch(this.handleError);
    }

    /**
     * post 请求
     * 
     * @param {any} url 
     * @param {any} [params] 
     * @returns {Observable<any>} 
     * @memberof DFHttp
     */
    post(url,params?,isToken?):Observable<any>{
        return this.http.post(url,params,{withCredentials: true}).catch(this.handleError);
    }

    getTestJSon(url):Observable<any>{
        return this.http.get(url);
    }

   /**
    * 网络异常捕捉
    * 
    * @private
    * @param {(Response|any)} error 
    * @returns 
    * @memberof DFHttp
    */
   private handleError(error:Response|any){
        console.log('************ network error ************')
        let errMsg:string;
        if(error instanceof Response){
            const body=error.json();
            const err=body.error || JSON.stringify(body);
            errMsg =`${error.status} - ${error.statusText || ''} ${err}`;
        }else{
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        console.log('************ network error end ************');
        return Observable.throw(errMsg);
   }
}
